import math
import cv2
import numpy as np
import matplotlib.pyplot as plt
import argparse
from mask import *

def get_barcode_width(img, show=False, func='median'):
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    min_r, max_r = 0, 0
    flag = True
    x, y = list(range(gray.shape[0])), []
    for r in x:
        if func == 'median':
            val = np.median(gray[r])
        elif func == 'mean':
            val = np.mean(gray[r])
        y.append(val)
        if val < 100 and flag:
            min_r = r
        elif val >= 100:
            max_r = r
            flag = False
    if show:
        plt.plot(x, y)
        plt.show()
    return min_r, max_r

if __name__=='__main__':
    parser = argparse.ArgumentParser()
    #parser.add_argument('-a', '--all', default=False, help='calc all plane')
    parser.add_argument('-f', '--file', default='./test.jpg', help='input picture')
    parser.add_argument('-c', '--cmd', default='getBarcodeWidth', help= \
            '''
            getBarcodeWidth: get barcode width of slice.
            getRect:         get rect in image.
            getMask:         get mask of slice.
            getText:         get text in image.
            ''')

    args = parser.parse_args()
    print(args)

    img_file = args.file
    img = cv2.imread(img_file)
    if args.cmd == 'getBarcodeWidth':
        min_r, max_r = get_barcode_width(img, True)
        #min_r, max_r = get_barcode_width(img, True, 'mean')
    elif args.cmd == 'getMask':
        fmask, smask, rmask = get_mask(img_file)
        cv2.imshow("fmask", fmask*127)
        cv2.imshow("smask", smask*127)
        cv2.imshow("rmask", rmask*127)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    elif args.cmd == 'getRect':
        pass
    elif args.cmd == 'getText':
        pass

        #img = cv2.imread('image/unfisheyeImage.jpg')
        #H_rows, W_cols= img.shape[:2]
        #H_rows, W_cols = 250, 500
        #print(H_rows, W_cols)

        ## 原图中书本的四个角点(左上、右上、左下、右下),与变换后矩阵位置
        #src_vertex = np.float32([[630, 873], [678, 594], [1314, 990], [1365, 717]])
        #dst_vertex = np.float32([[0, 0],[H_rows,0],[0, W_cols],[H_rows,W_cols]])

        #per = 0.5
        #_, gray, RedThresh, closed, opened = get_outline(img)
        #boxs, draws = get_vertex(img, opened, 4)
        #boxs.sort(key=lambda x: x[0][1], reverse=True)
        #for i in range(len(boxs)):
        #    #print(boxs[i])
        #    dst = perspective_transf(boxs[i], img)
        #    cv2.imshow(f'result{i}', resize(dst,    per))
        #    cv2.imshow(f'draw{i}',   resize(draws[i],   per))
        #cv2.imshow("test",cv2.resize(img, (0,0), fx=0.5, fy=0.5))
        #cv2.imshow("result",cv2.resize(dst, (0,0), fx=0.5, fy=0.5))
        #cv2.imshow("test", img)
        #cv2.imshow("result", dst)
        #cv2.imshow('gray',   resize(gray,   per))
        #cv2.imshow('closed', resize(closed, per))
        #cv2.imshow('opened', resize(opened, per))
